<?php
/**
 * 关键字模型
 * 
 * @version $Id: Keyword.php 664 2013-01-24 07:58:44Z linsir123 $
 */
class modelKeyword
{
	/**
	 * [类别]关注
	 */
	const T_FOCUS = 'focus';
	
	/**
	 * [类别]品牌
	 */
	const T_BRAND = 'brand';
	
	/**
	 * @var 保存个数
	 */
	public $saveSize = 20;
	
	/**
	 * @var 缓存的过期时间(3天)
	 */
	public $cacheLifeTime = 259200;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		///
	}
	
	/**
	 * 取得某个分类下的查询关键字列表
	 * // 缓存2天
	 */
	public function getList($cId, $count = 5, $type = 0)
	{
		if (empty($cId)) 
			return array();
			
		///
		$type = $type==0 ? self::T_BRAND : self::T_FOCUS;
		$dir = $this->_getDir($cId);
		$file = "{$dir}/{$cId}_{$type}.php";
		if (file_exists($file)) {
			$time = filemtime($file);
			if (time() - intval($time) < $this->cacheLifeTime) 
				$list = require($file);
		}
		
		///
		if ( ! isset($list)) {
			$list = $this->_spider($cId, $type);
			
			///
			lpDir::make($dir);
			
			///
			file_put_contents($file, "<?php return ". var_export($list, true) .";");
		}
		
		///
		return array_slice($list, 0, $count);
	}
	
	
	/// 以下为私有方法 /// 
	
	
	/**
	 * 取得根目录
	 */
	private function _getDir($cId)
	{
		$md5 = md5($cId);
		///
		return CACHE_DIR.'keyword/'. $md5[0] .'/'. $md5[1];
	}
	
	/**
	 * 取得某个分类对应的关键字列表
	 * // 抓取`淘宝排行榜`
	 */
	private function _spider($cId, $type)
	{
		$list = array();
		$url = "http://top.taobao.com/level3.php?cat={$cId}&level3=&show={$type}&ad_id=&am_id=&cm_id=&pm_id=&up=false";
		$content = file_get_contents($url);
		if ($content) {
			$content = iconv("GBK", "UTF-8", $content);
			
			///
			$tmp = explode('<table class="textlist">', $content);
			$tmp = explode('<div class="pagination" style="clear:both;">', $tmp[1]);
			
			///
			$pattern = "/<a (.*)>(.*)<\/a>/";
			preg_match_all($pattern, $tmp[0], $m);
			if (is_array($m[2])) 
				$list = array_slice($m[2], 0, $this->saveSize);
		}
		
		///
		return $list;
	}
}
